import axios from "axios";
import toast from '../components/Toast/index'
import loading from "@/components/Loading/index";
//创建一个新的请求实例instance,instance.的用法和axios.的用法一致，可以使用instance({})、instance.get（）、instance.post()
const instance = axios.create({
  baseURL: 'https://cloud.passlink.cn/',
  timeout: 60000,
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {

  //加载动画
  loading.showLoading({duration:10000})
  try {
    let tokenString: any = localStorage.getItem('auth');
  
    if(tokenString !== '' && tokenString !== undefined && tokenString !== null){
      let token = JSON.parse(tokenString);
      if (token !== null && token.accessToken.length > 30) {
        // 在请求头中添加 accessToken
        config.headers.Authorization = `Bearer ${token.accessToken}`;
        // config.headers["Content-Type"] = 'application/json'; // 设置请求的 Content-Type 为 application/json
      }
    }
  
  }
  catch (error) {
    console.log(error)
    console.log("TOKEN错误")
  }

  // 在发送请求之前做些什么
  return config;
}, function (error) {
  // 对请求错误做些什么
  toast.showToast({ msg: "请求错误", type: "error", mask: false })
  return Promise.reject(error);
});


// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  //加载动画清除
  loading.hideLoading()

  if (response.status === 403) {
    toast.showToast({ msg: response.data.msg, type: "error", mask: false })
    console.log("请求错误")
  }

  if (response.status === 500) {
    toast.showToast({ msg: "服务器错误,请联系管理员！！！", type: "error", mask: false })
    console.log("请求错误")
  }
  //授权失败
  if (response.status === 414) {
    //删除
    localStorage.setItem("auth","")
    toast.showToast({ msg: "请重新登陆！！！", type: "error", mask: false })
    console.log("登陆失效")
  }
  //获取的返回信息
  try {
    if (response.data.code === 500 || response.data.code === 403) {
      toast.showToast({ msg: response.data.msg, type: "error", mask: false })
      console.log("请求错误")
    }
    if (response.data.code === 200 && response.data.msg !== "") {
      toast.showToast({ msg: response.data.msg, type: "success", mask: false })
    }
    if (response.data.code === 414) {
      //删除
      localStorage.setItem("auth","")
      toast.showToast({ msg: "请重新登陆！！！", type: "error", mask: false })
      console.log("登陆失效")
    }

  }
  catch (error) {
    toast.showToast({ msg: "响应错误，请联系管理员", type: "error", mask: false })
  }
 
  // 对响应数据做点什么
  return response;
},
 function (error) {

  if(error.response.status === 500){
    const urlString = "http://www.passlink.cn:80/"
    const url = window.location.href 
    toast.showToast({ msg: "响应错误，请确保网络已连接", type: "error", mask: false })
    //此处是网路中断时处理，原页面刷新
    if( url.includes("biography") || url.includes("editor")){
      window.location.href=urlString; 
    }
  
  }
  if (error.response.status === 509) {
      let html = error.response.data;
      let verifyWindow:any = window.open("","_blank","height=400,width=560");
      verifyWindow.document.write(html);
      verifyWindow.document.getElementById("baseUrl").value = "http://cloud.passlink.cn:8000/";
     }
  return Promise.reject(error);
});

//   
const callapi = <T>(method: string = "GET", url: string, data: any = {}, config = {}): Promise<T> => {
  const reqconfig: any = {
    method,
    url,
    params: method === "GET" ? data : {},
    data: method === "POST" ? data : {},
    ...config
  };
  return instance(reqconfig);
};

// 该函数接收一个 method 参数，表示 HTTP 请求方法，然后返回一个函数，该函数接收两个参数 url 和 data，并返回一个 Promise，Promise 的泛型类型为 T。
const createRequest = (method: string) => <T>(url: string, data: any = {}, config = {}): Promise<T> =>
  callapi<T>(method, url, data, config);

export const getApi = createRequest("GET");
export const postApi = createRequest("POST");
export const putApi = createRequest("PUT");
export const deleteApi = createRequest("DELETE");
